// 配置路由
import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
// 使用插件
Vue.use(VueRouter)
// 引入路由组件

// 引入store
import store from '@/store'
// 先把VueRouter原型对象的push，先保存一份
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace

// 重写push/replace方法
VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        originPush.call(this, location, resolve, reject)
    } else {
        originPush.call(this, location, () => {}, () => {})
    }
}
VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        originReplace.call(this, location, resolve, reject)
    } else {
        originReplace.call(this, location, () => {}, () => {})
    }
}


// 配置路由

let router = new VueRouter({
    // 配置路由
    routes,
    // 控制滚动行为
    scrollBehavior(to, from, savePosition) {
        return {
            y: 0
        }
    }
})

// 全局守卫，前置守卫
router.beforeEach(async (to, from, next) => {
    next()
    let token = store.state.user.token
    let name = store.state.user.userinfo.name
    if (token) {
        // 用户已经登录了不能去login
        if (to.path == '/login') {
            next('/home')
        } else {
            // 去的不是login
            if (name) {
                next()
            } else {
                try {
                    await store.dispatch("getUserInfo");
                    next()
                } catch (error) {
                    // token失效
                    // 清除token
                    await store.dispatch('userLogout')
                    next('/login')
                }
            }
        }
    } else {
        next()
    }
})

export default router